/**
 * 向后端记录日志
 */
import { Service, success } from '@gnlab/utils'
import dayjs from 'dayjs'
import config from '@/config'
import { type Services } from '@/services'
import { API } from '@/services/common/api'

const CLIENT_ID_KEY = 'quntool-client-id'
let clientId = localStorage.getItem(CLIENT_ID_KEY) ?? ''
function getClientId() {
  if (!clientId) {
    clientId = dayjs().format('YYYYMMDD.HHmmss') + '.' + Math.round(Math.random() * 10000)
    localStorage.setItem(CLIENT_ID_KEY, clientId)
  }
  return clientId
}

export async function sendNetLog(
  topic: string,
  message?: string | boolean | number | null | Record<string, unknown>,
) {
  const data = {
    topic,
    message,
    clientId: getClientId(),
  }
  NetLog.logger.debug(data)

  return !config.IN_DEVELOPMENT
    ? API<void>('/Test/NotifyTest', { data })
    : Promise.resolve(success())
}

export class NetLog extends Service<Services> {
  get clientId() {
    return getClientId()
  }

  readonly send = sendNetLog
}
